<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>统计视频渲染帧率</title>
</head>
<body>
  <video id="localVideo" style="width: 320px; height: 240px;" autoplay muted></video>
  <button id="videoBtn30">播放FPS30的视频</button>
  <button id="videoBtn60">播放FPS60的视频</button>
  <input id="frameGapCheckBox" type="checkbox">是否统计帧间隔
  <div id="div" style="white-space: pre-line;"></div>
  <script>
    let video = document.getElementById("localVideo");
    let btn30 = document.getElementById("videoBtn30");
    let btn60 = document.getElementById("videoBtn60");
    let frameGapCheckBox = document.getElementById("frameGapCheckBox");
    let div = document.getElementById("div");
    let frameIndex = 0;
    let timerId = 0;
    let lastTs = 0;
    let gapStr = '';
    if (video.requestVideoFrameCallback) {
      video.requestVideoFrameCallback(videoRender);
    } else {
      alert("当前浏览器不支持获取渲染帧率")
    }

    btn30.addEventListener('click', () => {
      video.src = './video_30.mov';
      startTimer();
    })

    btn60.addEventListener('click', () => {
      video.src = './video_60.mov';
      startTimer();
    })
    video.addEventListener('ended', () => {
      stopTimer();
    })

    function startTimer() {
      stopTimer();
      reset();
      timerId = setInterval(() => {
        onTimer();
      }, 1000);
    }

    function stopTimer() { 
      if (timerId > 0) {
        clearInterval(timerId);
        timerId = 0;
      }
    }

    function onTimer() {
      if (frameGapCheckBox.checked) {
        div.innerHTML += 'fps:' + frameIndex + '    [' + gapStr  + ']\r\n';
      } else {
        div.innerHTML += 'fps:' + frameIndex + '\r\n';
      }
      
      frameIndex = 0;
      gapStr = '';
    }

    function reset() {
      frameIndex = 0;
      lastTs = 0;
      div.innerHTML = '';
    }

    function videoRender (now) {
      ++frameIndex;
      if (frameGapCheckBox.checked && lastTs > 0) {
        gapStr += Math.round(now - lastTs) + ' ';
      }
      video.requestVideoFrameCallback(videoRender);
      lastTs = now;
    }
  </script>
</body>

